package com.cug.campus_sh_market_server.util;

import org.jetbrains.annotations.NotNull;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {

    /**
     * 写入文件到本地
     * @param multipartFile 文件
     */
    public static String writeFileToLocal(MultipartFile multipartFile){
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName = null;
        try {
            inputStream = multipartFile.getInputStream();
            fileName = multipartFile.getOriginalFilename();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            String dirPath = getDirPath();
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(dirPath);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            String fullPath = dirPath + fileName;
            os = new FileOutputStream(fullPath);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            return fullPath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    @NotNull
    private static String getDirPath() {
        return "/" + "appFile" + "/" + new SimpleDateFormat("yyyy" + "/" + "MM" + "/" + "dd").format(new Date()) + "/";
    }


}
